/**
 * @description 用于文件上传的接口
 */
import request from '@/utils/request'
import logger from '@/utils/logger'
import { ElMessage } from 'element-plus'

const MAX_FILE_SIZE = 50 * 1024 * 1024 // 50MB

/**
 * @description 上传文件
 * @param {File} file 要上传的文件
 * @returns {Promise|null} 上传结果或在文件过大时返回 null
 */
export const fetchUploadFile = async (file) => {
  if (file.size > MAX_FILE_SIZE) {
    const message = '上传文件大小不能超过 50MB!'
    ElMessage.error(message)
    logger.error(message, { fileName: file.name, fileSize: file.size })
    return null
  }
  const formData = new FormData()
  formData.append('file', file)
  try {
    const response = await request({
      url: '/publicapi/files/upload',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    return response
  } catch (error) {
    logger.error('文件上传失败', error)
    throw error
  }
}

/**
 * @description 通用文件上传适用于各种文件
 */
export const generalFileUpload = async (file) => {
  if (file.size > MAX_FILE_SIZE) {
    const message = '上传文件大小不能超过 50MB!'
    ElMessage.error(message)
    logger.error(message, { fileName: file.name, fileSize: file.size })
    return null
  }
  const formData = new FormData()
  formData.append('file', file)
  try {
    const response = await request({
      url: '/publicapi/files/uploadfile',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    return response
  } catch (error) {
    logger.error('文件上传失败', error)
    throw error
  }
}
